//
//  JCBillPreviewController.m
//  JiFengDaRen
//
//  Created by shouhan on 2018/5/18.
//  Copyright © 2018年 陈永发. All rights reserved.
//

#import "JCBillPreviewController.h"
#import "JCBillTableViewCell.h"
#import "JCBillSectionHeaderView.h"
#import "JCBillHeadView.h"
#import "JCRepayProgressController.h"
#import "JCPlanWebViewController.h"

@interface JCBillPreviewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView * previewTableView;

@property (nonatomic, strong) UIView * bottomView;

@property (nonatomic, strong) UIButton * resetBtn;// 账单重置

@property (nonatomic, strong) UIButton * submitBtn;//账单提交

@property (nonatomic, strong) JCBillHeadView * headerView;

@property (nonatomic, strong) NSMutableArray * dataSource;//数据源

@property (nonatomic, strong) NSMutableArray * arrSecAmount;

@property (nonatomic, strong) NSMutableArray * arrSecDate;

@property (nonatomic, strong) NSMutableArray * arrTransfer;


@end

@implementation JCBillPreviewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"账单预览";
    self.dataSource = [NSMutableArray array];
    self.arrSecAmount = [NSMutableArray array];
    self.arrSecDate = [NSMutableArray array];
    self.arrTransfer = [NSMutableArray array];
    [self previewTableView];
    
    [self initUI];
    
    [self DoRequset_R_plan_preview:self.resetBtn];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.arrSecAmount[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JCBillTableViewCell * cell = [JCBillTableViewCell tableViewCellWithTableView:tableView];
    [cell getAmount:self.arrSecAmount[indexPath.section][indexPath.row] andDate:self.arrSecDate[indexPath.section][indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return __I6Height(34);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * viewIdentfier = @"headView";
    JCBillSectionHeaderView * sectionHeadView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier];

    if(!sectionHeadView){
        sectionHeadView = [[JCBillSectionHeaderView alloc] initWithReuseIdentifier:viewIdentfier];
    }
    [sectionHeadView getAmount:[self.dataSource[section][@"totalMoney"] mutableCopy] andDate:[self.dataSource[section][@"day"] mutableCopy]];
    
    return sectionHeadView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return __I6Height(34)+__I6Height(10);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 圆角弧度半径
    CGFloat cornerRadius = 10.f;
    // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
    cell.backgroundColor = UIColor.clearColor;
    
    // 创建一个shapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
    // 创建一个可变的图像Path句柄，该路径用于保存绘图信息
    CGMutablePathRef pathRef = CGPathCreateMutable();
    // 获取cell的size
    // 第一个参数,是整个 cell 的 bounds, 第二个参数是距左右两端的距离,第三个参数是距上下两端的距离
    CGRect bounds = CGRectInset(cell.bounds, 0, 0);

    // CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
   if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
        // 初始起点为cell的左上角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 添加一条直线，终点坐标为右下角坐标点并放到路径中去
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
    } else {
        // 添加cell的rectangle信息到path中（不包括圆角）
        CGPathAddRect(pathRef, nil, bounds);
    }
    // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
    layer.path = pathRef;
    backgroundLayer.path = pathRef;
    // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
    CFRelease(pathRef);
    // 按照shape layer的path填充颜色，类似于渲染render
    // layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
    layer.fillColor = [UIColor whiteColor].CGColor;
    
    // view大小与cell一致
    UIView *roundView = [[UIView alloc] initWithFrame:bounds];
    // 添加自定义圆角后的图层到roundView中
    [roundView.layer insertSublayer:layer atIndex:0];
    roundView.backgroundColor = UIColor.clearColor;
    // cell的背景view
    cell.backgroundView = roundView;
    
    // 以上方法存在缺陷当点击cell时还是出现cell方形效果，因此还需要添加以下方法
    // 如果你 cell 已经取消选中状态的话,那以下方法是不需要的.
    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
    backgroundLayer.fillColor = [UIColor cyanColor].CGColor;

    [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
    selectedBackgroundView.backgroundColor = UIColor.clearColor;
    cell.selectedBackgroundView = selectedBackgroundView;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = __I6Height(34)+__I6Height(10);
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (UITableView *)previewTableView{
    if (!_previewTableView) {
        _previewTableView = [[UITableView alloc] initWithFrame:CGRectMake(__I6Width(15), 0, KScreenWidth-__I6Width(15)*2, KScreenHeight - KNAVIGATIONBARHEIGHT-__I6Height(110)) style:UITableViewStylePlain];
        _previewTableView.delegate = self;
        _previewTableView.dataSource = self;
        _previewTableView.backgroundColor = [UIColor colorWithHexString:@"#F5F9FC"];
        _previewTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _previewTableView.showsVerticalScrollIndicator = NO;
        self.headerView = [[JCBillHeadView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, __I6Height(80))];
        [_previewTableView setTableHeaderView:self.headerView];
        [self.view addSubview:_previewTableView];
    }
    return _previewTableView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.height.mas_offset(__I6Height(110));
        }];
    }
    return _bottomView;
}

- (void)initUI{
    
    [self bottomView];
    
    UIView * line = [UIView new];
    line.backgroundColor = [UIColor colorWithHexString:@"#E0E0E0"];
    [self.bottomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.bottomView);
        make.height.mas_offset(.5);
    }];
    
    self.resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.resetBtn setTitle:@"账单重置" forState:UIControlStateNormal];
    [self.resetBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.resetBtn.titleLabel.font = KSHSystemFont(14);
    [self.resetBtn addTarget:self action:@selector(resetBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:self.resetBtn];
    
    self.submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.submitBtn setTitle:@"提交账单" forState:UIControlStateNormal];
    [self.submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.submitBtn.titleLabel.font = KSHSystemFont(14);
    [self.submitBtn addTarget:self action:@selector(submitBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:self.submitBtn];
    
    [@[self.resetBtn,self.submitBtn] mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:10 leadSpacing:10 tailSpacing:10];
    
    [@[self.resetBtn,self.submitBtn] mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(__I6Width(15));
        make.right.equalTo(self.view).offset(-__I6Width(15));
    }];
    
    [self.resetBtn layoutIfNeeded];
    [self.submitBtn layoutIfNeeded];

    [self.resetBtn.layer insertSublayer:[UIColor setGradualChangingColor:self.submitBtn fromColor:@"#55B0F7" toColor:@"#0E8AEC"] atIndex:0];
    [self.submitBtn.layer insertSublayer:[UIColor setGradualChangingColor:self.submitBtn fromColor:@"#55B0F7" toColor:@"#0E8AEC"] atIndex:0];
    self.resetBtn.layer.masksToBounds = YES;
    self.resetBtn.layer.cornerRadius = 5;
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = 5;
}

- (void)DoRequset_R_plan_preview:(UIButton *)btn{
    btn.enabled = NO;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [PPNetworkHelper POST:R_plan_preview parameters:self.dicData cache:NO encrypt:YES decode:NO responseCache:^(id responseCache) {
        
    } success:^(id result) {
        NSLog(@"result : %@",result);
        
        if ([result[@"success"] boolValue] == YES) {
            [self.dataSource removeAllObjects];
            [self.headerView getTotalFee:result[@"data"][@"totalFee"]];
            [self.headerView getStrAmount:self.strAmount andCount:[NSString stringWithFormat:@"%@",result[@"data"][@"count"]]];
            [self.dataSource addObjectsFromArray:result[@"data"][@"data"]];
            NSString * strAmount, *strTimes;
            [self.arrSecAmount removeAllObjects];
            [self.arrSecDate removeAllObjects];
            [self.arrTransfer removeAllObjects];
            for (NSDictionary * dic in self.dataSource) {
                strAmount = dic[@"tradeAmount"];
                strTimes = dic[@"times"];
                [self.arrSecAmount addObject:[strAmount componentsSeparatedByString:@","]];
                [self.arrSecDate addObject:[strTimes componentsSeparatedByString:@","]];
                [self.arrTransfer addObject:[dic[@"transferTimes"] componentsSeparatedByString:@","]];
            }
            
            [self.previewTableView reloadData];

        }else{
            [self.view makeToast:result[@"data"] duration:2.f position:@"center"];
        }
        btn.enabled = YES;
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    } failure:^(NSError *error) {
        btn.enabled = YES;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:error.localizedDescription duration:2.f position:@"center"];
    }];
}

- (void)DoRequsetR_get_repay_plan:(UIButton *)btn{
    btn.enabled = NO;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    NSString *deviceUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [dic setValue:deviceUUID forKey:@"device_id"];
    [dic setValue:self.dicData[@"cardNo"] forKey:@"cardNo"];
    [dic setValue:self.dicData[@"channel_type"] forKey:@"channel_type"];
    [dic setValue:self.dataSource forKey:@"data"];
    [dic setValue:self.strProvince forKey:@"province_name"];
    [dic setValue:self.strCity forKey:@"city_name"];
//    [dic setValue:[self.arrTransfer componentsJoinedByString:@","] forKey:@"transferTimes"];

    [PPNetworkHelper POST:R_get_repay_plan parameters:dic cache:NO encrypt:YES decode:NO responseCache:^(id responseCache) {
        
    } success:^(id result) {
        
        if ([result[@"success"] boolValue] == YES) {
            if ([result[@"data"][@"status"] boolValue] == NO) {
                NSString * html = [result[@"data"][@"page"] base64DecodedString];
                JCPlanWebViewController * web = [[JCPlanWebViewController alloc] init];
                web.url = html;
                web.title = @"创建还款计划";
                [self.navigationController pushViewController:web animated:YES];
            }else{
                [self.view makeToast:@"创建成功" duration:2.f position:@"center"];
                JCRepayProgressController * VC = [[JCRepayProgressController alloc] init];
                VC.type = 1;
                [self.navigationController pushViewController:VC animated:YES];
            }
        }else{
            [self.view makeToast:result[@"data"] duration:2.f position:@"center"];
        }
        btn.enabled = YES;
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    } failure:^(NSError *error) {
        btn.enabled = YES;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

// 重置账单
- (void)resetBtnAction:(UIButton *)btn{
    
    [self DoRequset_R_plan_preview:btn];
}

// 提交账单
- (void)submitBtnAction:(UIButton *)btn{
    [self DoRequsetR_get_repay_plan:btn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
